/*!
 * New Basic Strategy.
 * Date: 2015/12/31.
 * Copyright© 2014-2015 Vamaker All Rights Reserved.
 */
require([
  'jquery',
	'pageInit',
	'formValidator',
  'formAjax',
  'notification',
  'dateRange',
  'moment'
], function ($, vamakerPage, formValidator, formAjax, VamOpMsg, DateRange, moment) {
  $(function () {
    var $rangeDateBtn = $('#range-date-btn'),
      $rangeDate = $('#range_date'),
      startDate = $('#start-range-date').val() || moment().format(),
      endDate = $('#end-range-date').val() || moment().add(30, 'month').format(),
      dateStart = $('#start-date').val() || startDate,
      dateEnd = $('#end-date').val() || endDate,
      dateRange = new DateRange(),
      selectDate;
    dateRange.dateRange(
      $rangeDateBtn, {
        singleDatePicker: false,
        minDate: startDate,
        maxDate: endDate,
        startDate: dateStart,
        endDate:  dateEnd
      }, function (start, end, label) {
        selectDate = start.format('YYYY-MM-DD') + ' - ' + end.format('YYYY-MM-DD');
        $rangeDate.val(selectDate).trigger('blur');
    });
  });
  $(function () {
    var $belongLaunch = $('#belong_launch');
    $belongLaunch.on('change', function(evt) {
      var $me = $(this),
      meVal = $me.val();
      evt.preventDefault();
      $.ajax({
        url: VAM.getVar('SWTICH_CAMPAIGN_URL'),
        type: 'GET',
        dataType: 'JSON',
        data: {
          campaign_id: meVal,
          type: 'switchCampaign',
          rnd: (new Date()).getTime()
        }
      })
      .done(function (data) {
        var startDate = data['startDate'] || moment().format(),
        endDate = data['endDate'] || moment().add(30, 'month').format(),
        $rangeDate = $('#range_date'),
        dateRange = new DateRange(), 
        selectDate;
        // console.log(data);
        $('.min-budget-num').text(data['minBudget']);
        $('.max-budget-num').text(data['totalBudget']);

      if (data['totalBudget'] < data['minBudget']) {
        $('#budget_num_err').html(VAM.j('Budget shortfalls'));
      } else {
         $('#budget_num_err').html('');
      }

        $('#date-range-text').text(startDate + ' - ' + endDate);
        $('#range_date').val(moment(startDate).format('YYYY-MM-DD') + ' - ' + moment(endDate).format('YYYY-MM-DD'));
        dateRange.dateRange(
          $('#range-date-btn'), {
            singleDatePicker: false,
            minDate: startDate,
            maxDate: endDate,
            startDate: startDate,
            endDate:  endDate
          }, function (start, end, label) {
            selectDate = start.format('YYYY-MM-DD') + ' - ' + end.format('YYYY-MM-DD');
            $rangeDate.val(selectDate).trigger('blur');
        });
      })
      .fail(function () {
        console.log("error");
      })
      .always(function () {

      });
    });
  });
  $(function () {
    var $dataFrm = $('#data-frm'),
        $submitBtn = $dataFrm.find('button[type="submit"]'),
        $biddingType = $dataFrm.find('.bid-type'),
        $bidSetting = $dataFrm.find('.bid-setting'),
        $rtbBid = $('#rtb_bid'),
        $pmpBid = $('#pmp_bid'),
        $pmpId = $('#pmp_id'),
        pmpBidUrl = VAM.getVar('PMP_FIXED_BID'),
        $bidSettingChecked = $bidSetting.filter(':checked'),
        dataFieldRule, options, dataValidator, validateCallback,
        $operateBtn = $submitBtn.filter('.save-btn'),
        $operateType = $dataFrm.find('.operate-type'),
        strategyName = $('#strategy_name').val(),
        $minBudgetNum = $dataFrm.find('.min-budget-num'),
        $maxBudgetNum = $dataFrm.find('.max-budget-num'),
        $constantBiddingNum = $('#constant_bidding_num'),
        $pcpTargetBiddingNum = $('#pcp_target_bidding_num'),
        $pcpMaxBiddingNum = $('#pcp_max_bidding_num'),
        $ctrTargetBiddingNum = $('#ctr_target_bidding_num'),
        $ctrMaxBiddingNum = $('#ctr_max_bidding_num'),
        $budgetNum = $('#budget_num');
        validateCallback = function (evt) {
          var $me = $(this),
          meVal = $me.val()
          errorBox = $me.data('err'),
          $errorBox = $('#' + errorBox),
          flag = true,
          bidType = $('.bid-type:checked').val(),
          isCpcBid = evt.target.id === 'pcp_target_bidding_num' || evt.target.id === 'pcp_max_bidding_num',
          isCtrBid = evt.target.id === 'ctr_target_bidding_num' || evt.target.id === 'ctr_max_bidding_num',
          isFixedBid = evt.target.id === 'constant_bidding_num',
          msg = '';
          if (meVal === '' && (bidType === '1' && isFixedBid)) {
            flag = false;
            msg = VAM.j('Bidding cannot br empty');
          } else if (meVal === '' && (bidType === '2' && isCpcBid)) {
            flag = false;
            msg = VAM.j('Bidding cannot br empty');
          } else if (meVal === '' && (bidType === '3' && isCtrBid)) {
            flag = false;
            msg = VAM.j('Bidding cannot br empty');
          } else if (meVal !== '' && !/^(\d*\.)?\d+$/.test(meVal)) {
            flag = false;
            msg = VAM.j('Only input numbers');
          } else if (parseFloat(meVal) <= 0) {
            flag = false;
            msg = VAM.j('Enter a minimum of 0.01￥');
          };
          if (!flag) {
            msg = '<em class="checky-default-failure">' + msg + '</em>';
            $errorBox.html(msg);
          } else {
            $errorBox.html('');
          };
        };
      $constantBiddingNum.on('blur', validateCallback);
      $pcpTargetBiddingNum.on('blur', validateCallback);
      $pcpMaxBiddingNum.on('blur', validateCallback);
      $ctrTargetBiddingNum.on('blur', validateCallback);
      $ctrMaxBiddingNum.on('blur', validateCallback);
      
      $pmpId.on('blur', function(){
        var $me = $(this),
        meVal = $me.val()
        errorBox = $me.data('err'),
        $errorBox = $('#' + errorBox),
        flag = true,
        msg = '';
        if (meVal === '') {
          flag = false;
          msg = VAM.j('PMP ID cannot be empty');
        } else if (!/^(\d*\.)?\d+$/.test(meVal)) {
          flag = false;
          msg = VAM.j('Only input numbers');
        };
        if (!flag) {
          msg = '<em class="checky-default-failure">' + msg + '</em>';
          $errorBox.html(msg);
        } else {
          $errorBox.html('');
        };
      });
      // console.log($dataFrm);
    $submitBtn.on('click', function (evt) {
      var $me = $(this),
        operate = $me.data('operate'),
        operateTxt;
      operateTxt = '.' + operate + '-btn';
      $operateBtn = $submitBtn.filter(operateTxt);
      $operateType.val(operate);
    });

    $bidSetting.on('change', function(){
      var $me = $(this),
          meVal = $me.val();
      if (meVal === '0') {
        $rtbBid.removeClass('hidden');
        $pmpBid.addClass('hidden');
      } else {
        $pmpBid.removeClass('hidden');
        $rtbBid.addClass('hidden');
      }
    });

    $('.bid-type').on('change', function(){
      var meVal = $(this).val();
      if (meVal !== '2') {
        $('#pcp_target_bidding_num_err').html('');
        $('#pcp_max_bidding_num_err').html('');
      } else if (meVal !== '1') {
        $('#constant_bidding_num_err').html('');
      } else if (meVal !== '3') {
        $('#ctr_target_bidding_num_err').html('');
        $('#ctr_max_bidding_num_err').html('');
      }
    })
    $bidSettingChecked.trigger('change');

    // Get PMP Fixed Bid 
    $('#pmp_id').on('change', function (evt) {
      var $me = $(this),
        $fixedBid = $('#fixed_bid'),
        newValue = $me.val(),
        opData;
        opData = {
          newValue: newValue,
          rnd: (new Date()).getTime()
        };
        $fixedBid.val('');
        if (!!newValue) {
          $.ajax({
            url: pmpBidUrl,
            data: opData,
            type: 'post',
            success: function (data) {
              if (data.status === 'success') {
                VamOpMsg.messager(data);
                $fixedBid.val(data.bid);
              } else {
                // $('#pmp_id_err').html('<em class="checky-default-failure">' + VAM.j('Get PMP price failure') + '</em>')
                VamOpMsg.messager(data);
              }
            },
            error: function(){
              $('#pmp_id_err').html('<em class="checky-default-failure">' + VAM.j('Get PMP price failure') + '</em>');
            },
            always: function () {
              // $me.prop('readonly', false);
            }
          });
        };
    });

    dataFieldRule = {
      strategy_name:{
        rule:{
            required:{
                message:VAM.j('Solution name cannot be empty')
            }
        },
        messageContainer:'strategy_name_err'
      },
      budget_num:{
        rule:{
          required:{
            message:VAM.j('Budget cannot be empty')
          },
          floatnumber:{
            message:VAM.j('Only float number')
          },
          minval:{
            param: parseFloat('0.01'),
            message:VAM.j('Enter a minimum of 0.01￥')
          },
          // maxval: {
          //   param: parseFloat($maxBudgetNum.val()),
          //   message: '预算金额最大不能超过' + $maxBudgetNum.val() + '元'
          // },
          effectiveNumber:{
            message:VAM.j('Keep two decimal')
          }
        },
        messageContainer:'budget_num_err'
      },
      range_date: {
        rule: {
          required: {
            message: VAM.j('Time range cannot be empty')
          }
        },
        messageContainer: 'range_date_err'
      }
    };
    options = {
      submitOnSucceed: false,
      onvalidate: function(evt) {
        if (evt.resultList.length <= 0) {
          var $budgetNum = $('#budget_num'),
          $budgetNumErr = $('#budget_num_err'),
          biddingType = $biddingType.filter(':checked').val(),
          bidSettingChecked = $bidSetting.filter(':checked').val(),
          strategyName = $('#strategy_name').val(),
          minBudgetNum = parseFloat($minBudgetNum.text()),
          maxBudgetNum = parseFloat($maxBudgetNum.text()),
          budgetNum = parseFloat($budgetNum.val());
          if (budgetNum > maxBudgetNum) {
            $budgetNumErr.html('<em class="checky-default-failure">'+ VAM.j('The maximum budget amount cannot exceed') + maxBudgetNum + VAM.j('￥') +'</em>');
            return;
          } else if (budgetNum < minBudgetNum) {
            $budgetNumErr.html('<em class="checky-default-failure">'+ VAM.j('The minimum budget amount cannot under') + minBudgetNum + VAM.j('￥') +'</em>');
            return;
          } else {
            $budgetNumErr.html('');
          };

          // PMP ID Validate
          if (bidSettingChecked === '1') {
            $pmpId.trigger('blur');
            if ($('#pmp_id_err').html() !== '') {
              // $('#pmp_id_err').html('<em class="checky-default-failure">' + VAM.j('Get PMP price failure') + '</em>');
              event.preventDefault();
              return false;
            }
            // $pmpId.trigger('blur');
          } else {
            if (biddingType === '1') {
              $constantBiddingNum.trigger('blur');
              if ($('#constant_bidding_num_err').html() !== '') {
                // evt.preventDefault();
                event.preventDefault();
                return false;
              };
            } else if (biddingType === '2') {
              $pcpTargetBiddingNum.trigger('blur');
              $pcpMaxBiddingNum.trigger('blur');
              if ($('#pcp_target_bidding_num_err').html() !== '' || $('#pcp_max_bidding_num_err').html() !== '') {
                // evt.preventDefault();
                event.preventDefault();
                return false;
              };
            } else {
              $ctrTargetBiddingNum.trigger('blur');
              $ctrMaxBiddingNum.trigger('blur');
              if ($('#ctr_target_bidding_num_err').html() !== '' || $('#ctr_max_bidding_num_err').html() !== '') {
                // evt.preventDefault();
                event.preventDefault();
                return false;
              };
            };
          };
          // console.log(bidSettingChecked);
          $dataFrm.ajaxSubmit({
            beforeSubmit: function() {
              $operateBtn.button('loading');
            },
            success: function (data) {
              var next = $operateBtn.data('operate');
              $operateBtn.button('reset');
              if (data.status === 'success') {
                VamOpMsg.messager(data);
                if (next === 'save-next') {
                  window.location.href = VAM.getVar('NEXT_URL') + '?solution_id=' + data.data.id + '&strategy_name=' + strategyName;
                } else {
                  window.location.href = 'solution-list';
                };
              } else {
                VamOpMsg.messager(data);
              }
            }
          });
        };
      }
    };
    // dataValidator = new SL.Checky($dataFrm, dataFieldRule, options);
    formValidator.validate($dataFrm, dataFieldRule, options);
    dataValidator = formValidator.dataValidator;
    dataValidator.addRule('effectiveNumber',function(val, opt){
      return !!(val && /^\d+(\.\d{1,2})?$/.test(val));
    });
    dataValidator.addRule('validnum1', function(val, opt){
      opt.trigger('change');
      return true;
    });
    dataValidator.addRule('validnum2', function(val, opt){
      return parseInt(opt.val()) <= parseInt(val);
    });
  });
});
